<?php namespace sacvoyage;


require_once 'sacvoyage/autoload.php';
spl_autoload_register('sacvoyage\autoload');

require_once("sacvoyage/util.php");

use \sacvoyage\storage\Gateway;
use \sacvoyage\http\Globals;
use \sacvoyage\storage\Storage;
use \sacvoyage\domain\Domain;
use \sacvoyage\http\Site;

use \sacvoyage\exception\AuthException;
use \sacvoyage\exception\InputException;
use \sacvoyage\exception\InternalException;




// remove prefix if sacvoyage is installed not in root
$parts=parse_url($_SERVER["REQUEST_URI"]);
$fullPath=$parts['path'];
if($fullPath==$CONFIG['URL']['BASE']) {
	$path='/';
} elseif(starts_with($fullPath, $CONFIG['URL']['BASE'])) {
	$path=substr($fullPath, strlen($CONFIG['URL']['BASE']));
} else {
	die(
		"Url '{$fullPath}' was requested, ".
		"while sacvoyage is set up to run from '{$CONFIG['URL']['BASE']}'. ".
		"Suppose your redirections are wrong."
	);
}

Globals::setSiteBaseurl(
	rtrim($CONFIG['URL']['HOST'], '/').$CONFIG['URL']['BASE']
);



// init and run
$site=new Site(new Domain(new Storage(new Gateway(
	$CONFIG['DB']['HOST'],
	$CONFIG['DB']['NAME'],
	$CONFIG['DB']['USER'],
	$CONFIG['DB']['PASSWORD']
))));

try {
	$site->serve($path);
} catch(InputException $e) {
	header('400 Bad Request', true, 400);
	echo '{"status":"error","message":"request error'.$e->getMessage().'"}';
} catch(InternalException $e) {
	header('500 Internal Server Error', true, 500);
	// maybe it's better not to show message exception
	echo '{"status":"error","message":"internal server error'.$e->getMessage().'"}';
} catch(\Exception $e) {
	// theoretically that should never happen
	echo '{"status":"error","message":"'.$e->getMessage().'"}';
}



?>